package com.jxl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jxl.entity.po.Route;
import com.jxl.entity.po.RouteStation;
import com.jxl.entity.po.Station;
import com.jxl.entity.query.StationPageQuery;
import com.jxl.entity.vo.PageResponse;
import com.jxl.entity.vo.StationVO;
import com.jxl.entity.vo.UserVO;
import com.jxl.exception.BaseException;
import com.jxl.mapper.StationMapper;
import com.jxl.service.IRouteService;
import com.jxl.service.IRouteStationService;
import com.jxl.service.IStationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 站点表 服务实现类
 * </p>
 *
 * @author 金小梁
 * @since 2025-06-08
 */
@Service
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements IStationService {

    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private IRouteStationService routeStationService;
    /**
     * 分页查询站点信息
     *
     * @param stationPageQuery
     * @return
     */
    @Override
    public PageResponse<StationVO> queryStations(StationPageQuery stationPageQuery) {
        PageHelper.startPage(stationPageQuery.getPageNum(), stationPageQuery.getPageSize());
        Page<StationVO> stationVOPage = stationMapper.selectByPageQuery(stationPageQuery);
        PageResponse<StationVO> pageResponse = PageResponse.of(stationVOPage,  StationVO.class);
        return pageResponse;
    }

    /**
     * 删除站点
     *
     * @param stationIds
     */
    @Override
    public void deleteByIds(List<Integer> stationIds) {
        //查询线路中是否包含该站点
        stationIds.forEach(stationId -> {
            List<RouteStation> list = routeStationService.query().eq("station_id", stationId).list();
            if (list.size()>0) {
                throw new BaseException("该站点正在被线路使用，请先取消线路使用");
            }
        });
        removeByIds(stationIds);
    }

    /**
     * 根据线路id查询站点
     *
     * @param id
     * @return
     */
    @Override
    public List<StationVO> listById(Integer id) {
        //查出线路中包含的站点id
        List<RouteStation> routeStations = routeStationService.query().eq("route_id", id).list();
        List<Long> stationIds = routeStations.stream().map(RouteStation::getStationId).toList();
        //根据站点id查询站点信息
        List<Station> stations = listByIds(stationIds);
        List<StationVO> stationVOS = BeanUtil.copyToList(stations, StationVO.class);
        return stationVOS;
    }
}
